package com.mvd.app.ac2021.activitys.adapter;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.lzy.okgo.OkGo;
import com.mvd.app.R;
import com.mvd.app.activity.PhotoPreviewActivity;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.Constants;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.SystemUtil;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.RecheckCarsModel;
import com.mvd.app.model.TypeModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.mvd.app.application.BaseApplication.WAIJIAN_PHOTO_PREVIEW_LISTS;

// 车辆唯一性检查拍照


public class UniquenessPhotoActivity extends TakePhotoActivity implements AdapterView.OnItemClickListener,
        ApiConfig {


    @BindView(R.id.ac_unqueness_ib_back)
    ImageButton acUnquenessIbBack;
    @BindView(R.id.ac_unqueness_title_txt)
    TextView acUnquenessTitleTxt;
    @BindView(R.id.ac_unqueness_iv_headtip)
    ImageView acUnquenessIvHeadtip;
    @BindView(R.id.ac_unquenessbao_photo_photo_listview)
    ListView acUnquenessbaoPhotoPhotoListview;
    @BindView(R.id.ac_unquenessbao_photo_btn_other_imags)
    Button acUnquenessbaoPhotoBtnOtherImags;
    @BindView(R.id.ac_unquenessbao_photo_btn_buhege2)
    Button acUnquenessbaoPhotoBtnBuhege2;
    @BindView(R.id.ac_unquenessbao_photo_btn_wancheng2)
    Button acUnquenessbaoPhotoBtnWancheng2;
    @BindView(R.id.ac_unquenessbao_photo_photo_ll_bottom_layout)
    LinearLayout acUnquenessbaoPhotoPhotoLlBottomLayout;
    @BindView(R.id.ac_unquenessbao_photo_photo_scrollview)
    ScrollView acUnquenessbaoPhotoPhotoScrollview;
    private UniquenessPhotoActivity instances = null;
    private String carNo = null;//车牌号码
    private String PHOTO_TYPE = null;//外检拍照的TYPE上传类型
    private int CHECK_MODE = 0;//检测模式 0:外检  1：路试 2：底盘动态
    private String Item_Code = "";//F1外检,R1路试，DC底盘动态

    TakePhoto takePhoto;
    Uri imageUri;
    private RecheckCarsModel carsInforModel;
    private String isYasuoPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_uniqueness_photo);
        ButterKnife.bind(this);


        instances = this;
        isYasuoPhoto = SharedPreferencesUtils.getIsYasuoPhoto(instances);
        init();

//        carsInforModel = (RecheckCarsModel) getIntent().getSerializableExtra("re_model");
//        UtilsLog.e("recheckCarsModel==" + carsInforModel.toString());
//        String logStr = "\n" + "补传照片--车辆信息--环保--carsInforModel-" + "\n" +
//                "carsInforModel:" + "\n" +carsInforModel.toString()+ "\n" ;
//        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//
//        carNo = carsInforModel.getPlateRegion() +carsInforModel.getPlateNO();
        CHECK_MODE = BaseApplication.JIANCE_MODE;
//        UtilsLog.e("WaiJianPhotoActivity---CHECK_MODE==" + CHECK_MODE);
//        Line = getIntent().getStringExtra("CarDetailsActivity_Line");
        switch (CHECK_MODE) {
            case 0:
                Item_Code = "F1";
                break;
            case 1:
                Item_Code = "R1";
                break;
            case 2:
                Item_Code = "DC";
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CommonUtils.isOnline(instances)) {
        } else {
            Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                    .LENGTH_LONG).show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @OnClick({R.id.ac_unquenessbao_photo_btn_other_imags, R.id.ac_unquenessbao_photo_btn_buhege2,
            R.id.ac_unquenessbao_photo_btn_wancheng2, R.id.ac_unqueness_ib_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ac_unqueness_ib_back:
                finish();
                break;
            case R.id.ac_unquenessbao_photo_btn_other_imags:
                break;
            case R.id.ac_unquenessbao_photo_btn_buhege2:
                break;
            case R.id.ac_unquenessbao_photo_btn_wancheng2:
                break;
        }
    }

    OnlineAdapter contentAdapter2;
    List<TypeModel> typeModelListAdapter = null;

    private void init() {
        typeModelListAdapter = new ArrayList<>();
        TypeModel typeModel = null;
        for (int i = 0; i < Constants.WAIJIAN_PHOTO_LISTS.length; i++) {
            typeModel = new TypeModel();
            typeModel.setName(Constants.WAIJIAN_PHOTO_LISTS[i][0]);
            typeModel.setCode(Constants.WAIJIAN_PHOTO_LISTS[i][1]);
            typeModelListAdapter.add(typeModel);
        }
        contentAdapter2 = new OnlineAdapter(instances, typeModelListAdapter,
                mListener);
        //实例化ContentAdapter2类，并传入实现类
        acUnquenessbaoPhotoPhotoListview.setAdapter(contentAdapter2);
        setListViewHeightBasedONChildren(acUnquenessbaoPhotoPhotoListview);
        acUnquenessbaoPhotoPhotoListview.setOnItemClickListener(instances);
    }

    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("photo", "拍照失败==" + msg);
        String logStr = "\n" + "环保--外检项目拍照----拍照失败==" + "\n" + msg;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        ArrayList<TImage> images = result.getImages();
        if (images != null && images.size() > 0) {
            String photo_file_path = images.get(0).getCompressPath();
            String photo_file_path2 = images.get(0).getOriginalPath();
            Log.e("photo", "拍照失败--path==" + photo_file_path);
            Log.e("photo", "拍照失败--path=22=" + photo_file_path2);
        }
    }

    //    String photo_file_path;
    String photo_file_path_OriginalPath;
    int FLAG = 1;//0:拍照   1：相册
    private List<String> flagImagesUrls = new ArrayList<>();
    private List<Integer> flagImagesUrlsPosition = new ArrayList<>();

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Log.e("photo", "111111111111");
        if (result != null) {
//            showImg(result.getImages());
            ArrayList<TImage> images = result.getImages();
            if (images != null && images.size() > 0) {
                //压缩后的图片路径，不压缩为null
//                photo_file_path = images.get(0).getCompressPath();
                Log.e("photo", "拍照成功--path=111=" + images.get(0).getOriginalPath());
                Log.e("photo", "拍照成功--path=Environment=" + Environment.getExternalStorageDirectory());
                ///storage/emulated/0
                if (FLAG == 1) {
                    //拍照
                    if (SystemUtil.getSystemModel().contains("GIONEE") || SystemUtil.getSystemModel().contains("gionee")) {
                        //金立手机的路线
                        photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                                .getOriginalPath().replace("my_images/", "").replace(external_path2,"");
                        Log.e("photo", "拍照成功-金立手机-path=22=" + photo_file_path_OriginalPath);
                    } else {
                        //其他手机
                        /***
                         * @question 拍照返回的照片的路径处理
                         * @method 有的手机返回的照片带有/storage/emulated/0，
                         * @method 有的不带，所以需要分别处理
                         * @import 找个地方划重点，考试要考的，TDM CD
                         */
                        if (images.get(0).getOriginalPath().contains("storage/emulated")) {
                            photo_file_path_OriginalPath = images.get(0).getOriginalPath().replace("my_images/", "").replace(external_path2,"");
                        } else {
                            photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                                    .getOriginalPath().replace("my_images/", "").replace(external_path2,"");
                        }
//                    photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                            .getOriginalPath().replace("my_images/", "");
                        Log.e("photo", "拍照成功--path=22=" + photo_file_path_OriginalPath);
                    }
                    try {
                        FileInputStream in = new FileInputStream(photo_file_path_OriginalPath);
                        Bitmap bitmap = BitmapFactory.decodeStream(in);
                        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));
                        intent.setData(uri);
                        instances.sendBroadcast(intent);
                    } catch (FileNotFoundException e) {
                        String ee = e.getMessage() + "===" + e.getLocalizedMessage() + "===" + e.getCause() + "===" + e.toString();
                        Log.e("photo", "拍照成功--通知相册刷新失败=" + ee);
                        e.printStackTrace();
                    }
                } else {
                    //相册
                    photo_file_path_OriginalPath = images.get(0)
                            .getOriginalPath().replace("my_images/", "").replace(external_path2,"");
                    Log.e("photo", "相册--path=2234343434=" + photo_file_path_OriginalPath);
                }
//                //原图片的路径
//                photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                        .getOriginalPath().replace("my_images/", "");
//                Log.e("photo", "拍照成功--path=22=" + photo_file_path_OriginalPath);
                if (!TextUtils.isEmpty(photo_file_path_OriginalPath)) {
                    //拍照不需要编辑的
                    if (isYasuoPhoto.equals("是")){
                        Luban.with(instances)
                                .load(new File(photo_file_path_OriginalPath))                     //传人要压缩的图片
                                .setCompressListener(new OnCompressListener() { //设置回调
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        Log.e("photo", "压缩成功后调用");
                                        //拍照压缩后上传
                                        getDataUploadPhoto(file, photo_file_path_OriginalPath);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                        Toast.makeText(instances, "图片压缩出现问题，请重试", Toast.LENGTH_LONG).show();
                                    }
                                }).launch();    //启动压缩
                    }else {
                        getDataUploadPhoto(new File(photo_file_path_OriginalPath), photo_file_path_OriginalPath);
                    }

                }
            }
        }
    }

    /**
     * 实现类，响应按钮点击事件
     */
    TypeModel typeModel;
    int TypeModel_Position = 0;
    private String img_imageUri_path;
    private OnlineAdapter.MyClickListener mListener = new OnlineAdapter.MyClickListener() {
        @Override
        public void myOnClick(int position, View v, int flag) {
            PHOTO_TYPE = typeModelListAdapter.get(position).getCode();
            TypeModel_Position = position;
            FLAG = flag;
            if (flag == 0) {
                //相册
                takePhoto = getTakePhoto();
                File file = new File(Environment.getExternalStorageDirectory(), external_path+"/temp_my_app/" + System
                        .currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=7777=" + imageUri);
                img_imageUri_path = imageUri.getPath();
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=888=" + imageUri.getPath());
                takePhoto.onPickFromDocuments();
                typeModel = new TypeModel();
                typeModel.setName(typeModelListAdapter.get(position).getName());
                typeModel.setCode(typeModelListAdapter.get(position).getCode());
                img_code = typeModel.getCode();

            } else if (flag == 1) {
//                takePicture();
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    takePicture();
//                } else {
                Log.e("photo", "takePhoto---takePhoto");
                takePhoto = getTakePhoto();
                TakePhotoOptions takePhotoOptions = new TakePhotoOptions.Builder().setCorrectImage(false).create();
                takePhoto.setTakePhotoOptions(takePhotoOptions);
//                    configCompress(takePhoto);
//                    File file = new File(Environment.getExternalStorageDirectory(), "/temp_my_app/" + System
//                            .currentTimeMillis() + ".jpg");
                File file = new File(Environment.getExternalStorageDirectory(), external_path+"/temp_my_app/" + System
                        .currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=7777=" + imageUri);
                img_imageUri_path = imageUri.getPath();
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=888=" + imageUri.getPath());
                takePhoto.onPickFromCapture(imageUri);
//                }
                typeModel = new TypeModel();
                typeModel.setName(typeModelListAdapter.get(position).getName());
                typeModel.setCode(typeModelListAdapter.get(position).getCode());
                img_code = typeModel.getCode();
            } else if (flag == 2) {
                //跳转到图片预览界面
                if (WAIJIAN_PHOTO_PREVIEW_LISTS.get(Integer.parseInt(PHOTO_TYPE)) != null) {
                    Intent intent_preview = new Intent(instances, PhotoPreviewActivity.class);
                    intent_preview.putExtra("key_integer", Integer.parseInt(PHOTO_TYPE));
                    startActivity(intent_preview);
                }
            }
        }
    };


    String img_code = "";

    //上传照片
    private void getDataUploadPhoto(final File file, final String file_name) {
//        Log.e("photo", "6666666");
//        UtilsLog.e("getDataUploadPhoto---url==" + SharedPreferencesUtils.getHuanBaoIP(instances) + Huanbao_UPLOAD_PHOTO);
//        String DetectionCategory = "1";
//        if (carsInforModel.getDetectionCategory().equals("00")) {
//            DetectionCategory = "2";
//        } else {
//            DetectionCategory = "1";
//        }
//        String str = "QueueID:" + carsInforModel.getQueueID() + "\n" +
//                "GUID:" + carsInforModel.getGUID() + "\n" +
//                "Times:" + carsInforModel.getTimes() + "\n" +
//                "PlatformSN:" + carsInforModel.getPlatformSN() + "\n" +
//                "SN:" + carsInforModel.getSN() + "\n" +
//                "PhotoDate:" + DateUtil.currentTime2() + "\n" +
//                "PhotoType:" + PHOTO_TYPE + "\n" +
//                "Type:" + carsInforModel.getType() + "\n" +
//                "PlateNO:" + carNo + "\n" +
//                "ImageType:" + img_code + "\n" +
//                "DetectionCategory:" + DetectionCategory + "\n" +
//                "DetectionDate:" + carsInforModel.getDetectDate() + "\n" +
//                "PlateType:" + carsInforModel.getPlateType() + "\n" +
//                "ItemCode:" + "F1" + "\n" +
//                "Line:" + "01" + "\n" +
//                "VIN:" + carsInforModel.getVIN() + "\n" +
//                "FileType:" + "jpg" + "\n";
//        UtilsLog.e("环保getDataUploadPhoto---json==" + str);
//
//        String logStr = "\n" + "环保---补传照片---json==" +
//                "\n" + "json::" + str + "\n";
//        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//        OkGo.<String>post(SharedPreferencesUtils.getHuanBaoIP(instances) + Huanbao_UPLOAD_PHOTO).tag(instances)
////                .params("PHOTO_TYPE", PHOTO_TYPE)
//                //guid
//                .params("QueueID", carsInforModel.getQueueID())
//                //guid
//                .params("GUID", carsInforModel.getGUID())
//                //次数
//                .params("Times", carsInforModel.getTimes())
//                //PlatformSN
//                .params("PlatformSN", carsInforModel.getPlatformSN())
//                //SN
//                .params("SN", carsInforModel.getSN())
//                //拍摄时间
//                .params("PhotoDate", DateUtil.currentTime2())
//                //照片类型-拍的哪里的照片，位置
////                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
//                .params("PhotoType", PHOTO_TYPE)
//                .params("PlateNO", carNo)
//                .params("ImageType", img_code)
//                //车辆类型
//                .params("Type", carsInforModel.getType())
//                //车牌号码，两个拼起来的
//                .params("CarNO", carNo)
//                //号牌类型
//                .params("PlateType", carsInforModel.getPlateType())
//                //拍照code F1表示外检
//                .params("ItemCode", "F1")
//                //外检车道，检测线代号
//                .params("Line", "01")
//                //车辆识别代码
//                .params("VIN", carsInforModel.getVIN())
//                .params("FileType", "jpg")
////                .params("FileType", FileUtils.getExtensionName(file.getName()))
//                .params("DetectionCategory", DetectionCategory)
//                .params("DetectionDate", carsInforModel.getDetectDate())
//                //照片
//                .params("zp", file)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onStart(Request<String, ? extends Request> request) {
//                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "加载中...");
//
//                    }
//
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        String result = response.body();
//                        UtilsLog.e("getDataUploadPhoto-result==" + result);
//
//                        String logStr = "\n" + "环保--补传照片--请求成功" +
//                                "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
//                                Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body();
//                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
////                        WAIJIAN_PHOTO_PREVIEW_LISTS.put(Integer.parseInt(PHOTO_TYPE), file);
//                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
//                                && !"[]".equals(result)) {
//                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
//                                    "");
//                            UtilsLog.e("getDataUploadPhoto-newResult==" + newResult);
//                            if ("ok".equalsIgnoreCase(newResult)) {
//
//                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
//                                typeModel.setColor(1);
//                                typeModelListAdapter.set(TypeModel_Position, typeModel);
//                                contentAdapter2.notifyDataSetChanged();
//                            } else {
//                                String logStr2 = "\n" + "环保--补传照片--失败" +
//                                        "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
//                                        Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body();
//                                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
//                                Toast.makeText(instances, "上传失败，请重新拍照", Toast.LENGTH_LONG).show();
//                            }
//                        } else {
//                            String logStr3 = "\n" + "环保--补传照片--失败" +
//                                    "\n" + "data::" + "没有数据" + "\n" + "result:" + response.body();
//                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
//                            UtilsLog.e("getDataUploadPhoto-result==" + "没有数据");
//                        }
//                        CommonUtils.hideLoadingDialog(instances);
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        super.onError(response);
//                        UtilsLog.e("getDataUploadPhoto-onError==" + response.body());
//                        UtilsLog.e("getDataUploadPhoto-onError==" + response.getException());
//                        String logStr = "\n" + "环保--补传照片-onError-失败" +
//                                "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
//                                Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body() + "\n" +
//                                response.getException() + "\n" + response.message();
//                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//
//                        Toast.makeText(instances, "上传照片失败，请重试", Toast.LENGTH_LONG).show();
//                    }
//                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
    }
}
